<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000px">
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        v-loading="formLoading"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">
          <Icon icon="ep:user" class="mr-5px" />
          基本信息
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="formData.userId" placeholder="请输入用户ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="formData.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="formData.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户级别" prop="userLevel">
              <el-input v-model="formData.userLevel" placeholder="请输入用户级别" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成长值" prop="growthValue">
              <el-input-number 
                v-model="formData.growthValue" 
                :min="0" 
                placeholder="请输入成长值" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列用于对齐 -->
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="验证失败原因" prop="verifyFailReason">
              <el-input v-model="formData.verifyFailReason" type="textarea" placeholder="请输入验证失败原因" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后订单时间" prop="lastOrderTime">
              <el-date-picker
                v-model="formData.lastOrderTime"
                type="datetime"
                placeholder="选择最后订单时间"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 出行统计 -->
        <el-divider content-position="left">
          <Icon icon="ep:odometer" class="mr-5px" />
          出行统计
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总出行公里数" prop="totalKilometers">
              <el-input-number 
                v-model="formData.totalKilometers" 
                :precision="2" 
                :min="0" 
                placeholder="请输入总出行公里数" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本月出行里程" prop="monthlyKilometers">
              <el-input-number 
                v-model="formData.monthlyKilometers" 
                :precision="2" 
                :min="0" 
                placeholder="请输入本月出行里程" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 财务信息 -->
        <el-divider content-position="left">
          <Icon icon="ep:wallet" class="mr-5px" />
          财务信息
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总充值金额" prop="totalRechargeAmount">
              <el-input-number 
                v-model="formData.totalRechargeAmount" 
                :precision="2" 
                :min="0" 
                placeholder="请输入总充值金额" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退款金额" prop="refundAmount">
              <el-input-number 
                v-model="formData.refundAmount" 
                :precision="2" 
                :min="0" 
                placeholder="请输入退款金额" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总订单支付金额" prop="totalPayAmount">
              <el-input-number 
                v-model="formData.totalPayAmount" 
                :precision="2" 
                :min="0" 
                placeholder="请输入总订单支付金额" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本月订单支付金额" prop="monthlyPayAmount">
              <el-input-number 
                v-model="formData.monthlyPayAmount" 
                :precision="2" 
                :min="0" 
                placeholder="请输入本月订单支付金额" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="可开发票金额" prop="invoiceableAmount">
              <el-input-number 
                v-model="formData.invoiceableAmount" 
                :precision="2" 
                :min="0" 
                placeholder="请输入可开发票金额" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行程未开票金额" prop="unInvoicedAmount">
              <el-input-number 
                v-model="formData.unInvoicedAmount" 
                :precision="2" 
                :min="0" 
                placeholder="请输入行程未开票金额" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getPassengerInfo, createPassengerInfo, updatePassengerInfo, type PassengerInfoVO } from '@/api/system/passengerinfo'

/** 乘客信息 表单 */
defineOptions({ name: 'PassengerInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  userId: undefined,
  username: undefined,
  nickname: undefined,
  realName: undefined,
  mobile: undefined,
  email: undefined,
  idCard: undefined,
  verifyFailReason: undefined,
  lastOrderTime: undefined,
  invoiceableAmount: undefined,
  unInvoicedAmount: undefined,
  userLevel: undefined,
  growthValue: undefined,
  totalKilometers: undefined,
  monthlyKilometers: undefined,
  totalRechargeAmount: undefined,
  refundAmount: undefined,
  totalPayAmount: undefined,
  monthlyPayAmount: undefined
})
const formRules = reactive({
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  realName: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
  mobile: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await getPassengerInfo(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PassengerInfoVO
    if (formType.value === 'create') {
      await createPassengerInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await updatePassengerInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    username: undefined,
    nickname: undefined,
    realName: undefined,
    mobile: undefined,
    email: undefined,
    idCard: undefined,
    verifyFailReason: undefined,
    lastOrderTime: undefined,
    invoiceableAmount: undefined,
    unInvoicedAmount: undefined,
    userLevel: undefined,
    growthValue: undefined,
    totalKilometers: undefined,
    monthlyKilometers: undefined,
    totalRechargeAmount: undefined,
    refundAmount: undefined,
    totalPayAmount: undefined,
    monthlyPayAmount: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.form-container {
  max-height: 600px;
  overflow-y: auto;
  padding: 0 10px;
}

:deep(.el-divider__text) {
  background-color: #fff;
  font-weight: 600;
  color: #303133;
}

:deep(.el-divider) {
  margin: 20px 0;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>